﻿using huqiang.Communication;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace UnityLogServer
{
    static class Program
    {
        public static AssetsSetting assets;
        static int Day;
        static int Hour;
        static int Min;
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            ReloadSetting();
            int port = assets.GetInt("net", "KcpPort");
            if (port < 1000)
                port = 8888;
            OutLog.Log2 = (link, str) =>
            {
                var user = link as NetUser;
                if (user != null)
                {
                    if (user.log == null)
                    {
                        if (user.Tag != null)
                        {
                            string folder = user.Tag;
                            var chars = System.IO.Path.GetInvalidPathChars();
                            if (user.Tag.IndexOfAny(chars) >= 0)
                            {
                                folder = user.endPoint.Address.ToString();
                            }
                            user.log = new Log(folder);
                            //user.log.Delete();
                        }
                    }
                    if (user.log != null)
                        user.log.Write(str);
                }
            };
            if (!IsPortOccupedFun2(port))
            {
                NetServer.Instance.OpenServer(port);
                Application.Run();
                NetServer.Instance.Dispose();
            }
        }
        internal static Boolean IsPortOccupedFun2(Int32 port)
        {
            System.Net.NetworkInformation.IPGlobalProperties iproperties = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties();
            System.Net.IPEndPoint[] ipEndPoints = iproperties.GetActiveUdpListeners();
            foreach (var item in ipEndPoints)
            {
                if (item.Port == port)
                {
                    return true;
                }
            }
            return false;
        }
        public static void ReloadSetting()
        {
            assets = new AssetsSetting("setting.ini", "setting.ini");
            INIReader build = new INIReader();
            build.LoadFromFile("build.ini");
            var sec = build.FindSection("missions");
            if (sec != null)
            {
                string time = sec.GetValue("buildTime");
                string[] ss = time.Split(':');
                int.TryParse(ss[0], out Hour);
                if (ss.Length > 1)
                {
                    int.TryParse(ss[1], out Min);
                    Min %= 60;
                }
            }
        }
    }
}
